package com.eqdd.yiqidian.ui.tongxunlu;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.TeamCheatInfoActivityCustom;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.SelectBean;
import com.eqdd.yiqidian.bean.rebuild.GroupListResultBean;
import com.eqdd.yiqidian.bean.rebuild.GroupMemberListResultBean;
import com.eqdd.yiqidian.bean.rebuild.ShareConf;
import com.eqdd.yiqidian.bean.rebuild.ShareEnterConf;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpPresneter;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonCallBack;
import com.eqdd.yiqidian.ui.MainActivity;
import com.eqdd.yiqidian.ui.share.ShareEnterActivity;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.jakewharton.rxbinding.view.RxView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.rong.calllib.RongCallClient;
import io.rong.imkit.RongIM;
import io.rong.imkit.RongKitReceiver;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import rx.schedulers.Schedulers;


public class TeamCheatInfoActivity extends BaseActivity {
    private static final int REQ_ADD_MEMBERS = 1;
    private static final int QUIT_GROUP = 2;
    private TeamCheatInfoActivityCustom dataBinding;
    private String groupid;
    private String groupname;
    private Intent mIntent;
    private AlertDialog alertTipDialog;
    private boolean isQunBoss = false;
    private AlertDialog alertTipJieSanDialog;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_team_cheat_info);

    }

    @Override
    public void initData() {
        groupid = getIntent().getStringExtra("groupid");
        groupname = getIntent().getStringExtra("groupname");
        initTopTitleBar(View.VISIBLE, groupname);
        refreshRy();
    }

    private void refreshRy() {
        OkGo.<HttpResult<List<GroupListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.SEARCH_GROUP)
                .params("groupname", groupname)
                .params("groupid", groupid)
                .params("userGuid", user.getGuid())
                .execute(new JsonCallBack<HttpResult<List<GroupListResultBean>>>() {
                    @Override
                    public void onSuccess(Response<HttpResult<List<GroupListResultBean>>> response) {
                        HttpResult<List<GroupListResultBean>> httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            if (httpResult.getItems() != null && httpResult.getItems().size() > 0) {
                                if (httpResult.getItems().get(0).getGroupCreater().equals(user.getGuid())) {
                                    isQunBoss = true;
                                    dataBinding.oivTeamManage.setVisibility(View.VISIBLE);
                                }
                            }
                            ImageUtil.setImage(httpResult.getItems().get(0).getGroupphoto(), dataBinding.ivGroupHead);
                        }
                    }
                });
    }

    @Override
    public void setView() {
        RxView.clicks(dataBinding.oivTeamManage)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString("groupid", groupid);
                    bundle.putString("groupname", groupname);
                    startActivity(TeamManageActivity.class, bundle);
                });
        dataBinding.oivTeamName.setRightText(groupname);
        RongIMClient.getInstance().getConversationNotificationStatus(Conversation.ConversationType.GROUP, groupid, new RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() {
            @Override
            public void onSuccess(Conversation.ConversationNotificationStatus conversationNotificationStatus) {
                dataBinding.sbShowNickName.setChecked(conversationNotificationStatus == Conversation.ConversationNotificationStatus.NOTIFY);
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                System.out.println(errorCode);
            }
        });
        dataBinding.sbShowNickName.setOnCheckedChangeListener((v, isCheckd) ->
                RongIM.getInstance().setConversationNotificationStatus(Conversation.ConversationType.GROUP
                        , groupid, isCheckd ? Conversation.ConversationNotificationStatus.NOTIFY : Conversation.ConversationNotificationStatus.DO_NOT_DISTURB, new RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() {
                            @Override
                            public void onSuccess(Conversation.ConversationNotificationStatus conversationNotificationStatus) {
                                System.out.println(isCheckd);
                                System.out.println("成功");
                                System.out.println(conversationNotificationStatus);
                            }

                            @Override
                            public void onError(RongIMClient.ErrorCode errorCode) {

                                System.out.println(errorCode);
                            }
                        })
        );
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_group_head:
                RxPermissions.getInstance(this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(isGrant -> {
                            if (isGrant) {
                                PictureSelector.create(TeamCheatInfoActivity.this)
                                        .openGallery(PictureMimeType.ofImage())
                                        .selectionMode(PictureConfig.SINGLE)
                                        .enableCrop(true)
                                        .withAspectRatio(500, 500)
                                        .freeStyleCropEnabled(false)
                                        .showCropFrame(true)
                                        .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                                        .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                                        .compress(true)
                                        .imageSpanCount(3)
                                        .isCamera(true)
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                            } else {
                                ToastUtil.showShort("请开启拍照权限");
                            }
                        });

                break;
            case R.id.oivTeamName:
                mIntent = new Intent(this, TeamNameSetActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("groupid", groupid);
                bundle.putString("groupname", groupname);
                startActivityForResult(TeamNameSetActivity.class, bundle, Config.TEAM_NAME_SET);
                break;
            case R.id.oivQRCordCard:
                mIntent = new Intent(this, QunErweimaActivity.class);
                mIntent.putExtra("groupid", groupid);
                mIntent.putExtra("groupname", groupname);
                startActivity(mIntent);
                break;
            case R.id.oivMemberList:
                Bundle bundle1 = new Bundle();
                bundle1.putString("groupid", groupid);
                startActivity(TeamMemberListActivity.class, bundle1);
                break;
            case R.id.oivAddMember:
                addMembers();
                break;
            case R.id.btnQuitTeam:
                if (isQunBoss) {
                    if (alertTipJieSanDialog == null) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setMessage("你确定要解散该群吗?");
                        builder.setTitle("提示");
                        builder.setPositiveButton("确认", (dialog, which) -> {
                            dialog.dismiss();
                            new HttpPresneter.Builder(HttpConfig.DISMISS_GROUP, String.class, this)
                                    .Params("userGuid", user.getGuid())
                                    .Params("Groupid", groupid)
                                    .setOnHttpListener(new HttpPresneter.OnHttpListener() {
                                        @Override
                                        public void onError(Throwable e) {

                                        }

                                        @Override
                                        public void onNext(Object o) {
                                            if (((String) o).contains("200")) {

                                                ToastUtil.showShort("解散群组成功");
                                                startActivity(MainActivity.class);
                                            }
                                        }
                                    })
                                    .build()
                                    .post();

                        });
                        builder.setNegativeButton("取消", (DialogInterface dialog, int which) -> {
                                    dialog.dismiss();
                                }
                        );
                        alertTipJieSanDialog = builder.create();
                    }
                    alertTipJieSanDialog.show();
                } else {
                    if (alertTipDialog == null) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setMessage("确认退出该群吗?");
                        builder.setTitle("提示");
                        builder.setPositiveButton("确认", (dialog, which) -> {
                            dialog.dismiss();
                            new HttpPresneter.Builder(HttpConfig.QUIT_GROUP, String.class, this)
                                    .Params("userGuid", ";" + user.getGuid())
                                    .Params("Groupid", groupid)
                                    .Params("GroupName", groupname)
                                    .setOnHttpListener(new HttpPresneter.OnHttpListener() {
                                        @Override
                                        public void onError(Throwable e) {

                                        }

                                        @Override
                                        public void onNext(Object o) {
                                            if (((String) o).contains("200")) {
                                                RongIM.getInstance().removeConversation(Conversation.ConversationType.GROUP, groupid
                                                        , new RongIMClient.ResultCallback<Boolean>() {
                                                            @Override
                                                            public void onSuccess(Boolean aBoolean) {
                                                                setResult(QUIT_GROUP);
                                                                startActivity(MainActivity.class);
                                                            }

                                                            @Override
                                                            public void onError(RongIMClient.ErrorCode errorCode) {

                                                            }
                                                        });
                                                ToastUtil.showShort("退出群组成功");
                                            }
                                        }
                                    })
                                    .build()
                                    .post();

                        });
                        builder.setNegativeButton("取消", (DialogInterface dialog, int which) -> {
                                    dialog.dismiss();
                                }
                        );
                        alertTipDialog = builder.create();
                    }
                    alertTipDialog.show();
                }
        }
    }


    /**
     * 拉人入群
     */
    private void addMembers() {
        OkGo.<HttpResult<List<GroupMemberListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.GROUP_USER_LIST)
                .params("groupid", groupid)
                .execute(new DialogCallBack<HttpResult<List<GroupMemberListResultBean>>>(TeamCheatInfoActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult<List<GroupMemberListResultBean>>> response) {
                        HttpResult<List<GroupMemberListResultBean>> httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            ShareConf shareConf = new ShareConf().setTitle("请选择")
                                    .setRightTitle("发送")
                                    .setEnabledBeans(httpResult.getItems())
                                    .setGuidField("Guid")
                                    .setEnableTip("已在该群组中")
                                    .setMaxTip("最多%d");

                            ShareEnterConf shareEnterConf = (ShareEnterConf) new ShareEnterConf()
                                    .setFriendConf(shareConf)
                                    .setQunChooseConf(shareConf)
                                    .setQunListConf(shareConf)
                                    .setQunMemberConf(shareConf)
                                    .setStaffConf(shareConf)
                                    .setShare(false)
                                    .setAll(false)
                                    .setTitle("请选择")
                                    .setRightTitle("发送")
                                    .setEnableTip("已在该群组中")
                                    .setMaxTip("最多%d")
                                    .setEnabledBeans(httpResult.getItems())
                                    .setGuidField("Guid");
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("bean", shareEnterConf);
                            startActivityForResult(ShareEnterActivity.class, bundle, Config.SHARE_ENTER);
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.CHANGE) {
            refreshRy();
        }
        switch (requestCode) {
            case Config.TEAM_NAME_SET:
                if (resultCode == Config.CHANGE) {
                    dataBinding.oivTeamName.setRightText(data.getStringExtra("groupname"));
                }
                break;
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                    OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.UPDATE_GROUP)
                            .params("groupid", groupid)
                            .params("groupphoto", new File(localMedia.get(0).isCompressed() ? localMedia.get(0).getCompressPath() : localMedia.get(0).getPath()))
                            .execute(new DialogCallBack<HttpResult>(TeamCheatInfoActivity.this) {
                                @Override
                                public void onSuccess(Response<HttpResult> response) {
                                    HttpResult httpResult = response.body();
                                    ToastUtil.showShort(httpResult.getMsg());
                                    if (httpResult.getStatus() == 200) {
                                        ImageUtil.setImage(new File(localMedia.get(0).isCompressed() ? localMedia.get(0).getCompressPath() : localMedia.get(0).getPath()), dataBinding.ivGroupHead);
                                    }
                                }
                            });
                    break;
            }
        }
        if (requestCode == Config.SHARE_ENTER && resultCode == Config.SUCCESS) {
            ArrayList<SelectBean> selectBeans = data.getParcelableArrayListExtra(Config.SELECTED_BEANS);
            OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.ADD_GROUP)
                    .params("userGuid", getUids(selectBeans))
                    .params("Groupid", groupid)
                    .params("GroupName", groupname)
                    .execute(new DialogCallBack<HttpResult>(TeamCheatInfoActivity.this) {
                        @Override
                        public void onSuccess(Response<HttpResult> response) {
                            HttpResult httpResult = response.body();
                            ToastUtil.showShort(httpResult.getMsg());
                            if (httpResult.getStatus() == 200) {

                            }
                        }
                    });
        }
    }

    private String getUids(ArrayList<SelectBean> selectBeans) {
        String uids = "";
        for (int i = 0; i < selectBeans.size(); i++) {
            uids += ";" + selectBeans.get(i).getGuid();
        }
        return uids;
    }

    @Override
    protected void onDestroy() {
        Schedulers.io().createWorker().schedule(() -> {
            PictureFileUtils.deleteCacheDirFile(TeamCheatInfoActivity.this);
        });
        super.onDestroy();
    }
}
